<template>
    <rect v-if="visible && startEvent && moveEvent && startXY" 
        :x="x" 
        :y="y"
        :width="width"
        :height="height"
        style="fill:rgb(0,0,255);fill-opacity:0.1;stroke-width:1;stroke:rgb(0,0,0);stroke-dasharray:5 5;"       
        :transform="`translate(${tx} ${ty})`"></rect>
</template>
<script>
export default {
    name: "svgPicker",
    data(){
        return {
            width:0,
            height:0,
            x:0,
            y:0,
            tx:0,
            ty:0,
            readonly:false
        }
    },    
    props:{
        startEvent:null,
        startXY:null,
        moveEvent:null,
        items:null,
        visible:false
    },  
    watch:{
        moveEvent(v,o){
            if(v && this.visible){
                this.width=Math.abs(this.moveEvent.clientX - this.startEvent.clientX);
                this.height=Math.abs(this.moveEvent.clientY - this.startEvent.clientY);
                if(this.moveEvent.clientX < this.startEvent.clientX){
                    this.tx=this.moveEvent.clientX - this.startEvent.clientX
                }else{
                    this.tx=0;
                }
                if(this.moveEvent.clientY < this.startEvent.clientY){
                    this.ty=this.moveEvent.clientY - this.startEvent.clientY
                }else{
                    this.ty=0;
                }               
            }
        },
        visible(v,o){
            if(v && !o){
                this.tx=0;
                this.ty=0;
                this.x=this.startXY.x;
                this.y=this.startXY.y;                
            }

            if(!v && o){
                this.getSelected();
            }
        }
    },  
    methods:{        
        getSelected:function(){
            if(!this.items || this.items.length<=0 || this.height<= 2 || this.width <= 2) return;
            var sXY={x:this.x,y:this.y};
            var eXY={x:this.x+this.width,y:this.y+this.height};
            if(this.tx<0){
                sXY.x=this.x+this.tx;
                eXY.x=this.x;
            }
            if(this.ty<0){
                sXY.y=this.y+this.ty;
                eXY.y=this.y;
            }

            var selected=[];
            
            this.items.forEach(element => {
                if(element.x >= sXY.x && element.y >= sXY.y && element.x+element.width <= eXY.x && element.y+element.height <= eXY.y){
                    selected.push(element);
                }
            });

            //console.log('getSelected',sXY,eXY,this.items,selected);
            this.$emit('select',selected);
        }
    }

}
</script>